package com.example.fwcz.service.impl;

import com.example.fwcz.entity.user;
import com.example.fwcz.mapper.UserMapper;
import com.example.fwcz.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService, UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    /**
     * 实现 UserDetailsService 接口
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException{
        user user=userMapper.searchOneuser(username);
        if(user==null){
            throw new UsernameNotFoundException("用户不存在");
        }
        return user;
    }
    // --- 以下重写 UserService ---
    @Override
    public user findUserByUsernameAndPassword(String username,String password){
        // username
        user user=userMapper.searchOneuser(username);
        if(user==null){
            throw new UsernameNotFoundException("用户不存在");
        }
        // password
        // may add HashUtils 进行转码操作
        return user;
    }
    @Override
    public void addUser(user user){
        if(userMapper.searchOneuser(user.getUsername())==null){
            throw new UsernameNotFoundException("用户不存在");
        }else{
            userMapper.addUser(user);
        }
    }
    @Override
    public void deleteUser(String username){
        if(userMapper.searchOneuser(username)==null){
            throw new UsernameNotFoundException("用户不存在");
        }else{
            userMapper.deleteUser(username);
        }
    }
   @Override
    public void changeUser(user user){
       if(userMapper.searchOneuser(user.getUsername())==null){
           throw new UsernameNotFoundException("用户不存在");
       }else{
           userMapper.changeUser(user);
       }
   }
    @Override
    public List<user> searchAlluser(){
        return userMapper.searchAlluser();
    }
    @Override
    public user searchOneuser(String username){
        if(userMapper.searchOneuser(username)==null){
            throw new UsernameNotFoundException("用户不存在");
        }else{
            return userMapper.searchOneuser(username);
        }
    }
}
